package com.aaa.filter;

import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

public class LogFilter implements Filter {
    // Logger 是异步线程，不阻塞当前的程序，sout 线上不能使用
    Logger logger = Logger.getLogger(LogFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("LogFilter----init()");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 不进行任何鉴权过滤，只获取参数
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取请求的url
        String url =  request.getRequestURI();
        StringBuilder stringBuilder = new StringBuilder();
        //追加“？”
        stringBuilder.append(url+"?");

        // 获取所有请求参数的键值对
        Map<String, String[]>  map = request.getParameterMap();

        for (String key:map.keySet()) {
            String[] strings = map.get(key);
            for (String value : strings) {
                stringBuilder.append(key + "=" + value + "&");
            }
        }
        // ？ 分割的是 路径与参数
        // &  分割的是参数
        logger.info("请求内容:"+stringBuilder.toString());
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        logger.info("LogFilter----destroy()");
    }
}
